﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace CommonLib.Audio
{

	public class AudioSubManager : MonoBehaviour
	{
		//
		protected int AudioCount { get; private set; } = 3;

		protected List<AudioSource> sourceList;
		protected Dictionary<string, AudioSource> sourcePlayingDic;

		protected virtual AudioSource NextSource {
			get
			{
				AudioSource source = null;
				for (int i = 0; i < sourceList.Count; i++)
				{
					//source isn`t playing And havn`t someone is setting data
					if(!sourceList[i].isPlaying && null == sourceList[i].clip)
					{
						source = sourceList[i];
						break;
					}
				}
				if (null != source)
					return source;
				else
					return BounceSourceList();
			}
		}

		public void Init()
		{
			sourcePlayingDic = new Dictionary<string, AudioSource>();
			sourceList = new List<AudioSource>();
			for (int i = 0; i < AudioCount; i++)
			{
				sourceList.Add(this.gameObject.AddComponent<AudioSource>());
			}
		}

		public void Play()
		{

		}

		internal void Play(string label, AudioDataBase data, float fadein, float fadeout)
		{
			//Set AudioSource Field
			AudioSource source = NextSource;
			//sign that go is setting aduio clip 
			source.clip = data.AudioClip;
			source.loop = data.Loop;
			source.volume = data.Volume;
			//Add PlayingList
			if(!string.IsNullOrEmpty(label))
				sourcePlayingDic.Add(label, source);
			//Listening for audio end playing
			if(source.loop)
				source.Play();
			else	
				StartCoroutine(CorPlayingAudio(label ,source));
		}

		protected int bounceCount = 2;
		protected virtual AudioSource BounceSourceList()
		{
			AudioSource source = null;
			for (int i = 0; i < bounceCount; i++)
			{
				source = this.gameObject.AddComponent<AudioSource>();
				sourceList.Add(source);
			}
			//Return Last One
			return source;
		}
		
		IEnumerator CorPlayingAudio(string label,AudioSource source)
		{
			source.Play();
			while(source.isPlaying)
				yield return null;
			if (!string.IsNullOrEmpty(label))
				sourcePlayingDic.Remove(label);
			//Enable source to NextSource
			source.clip = null;
		}
	}
}